import React from 'react';
import { Upload, Modal,notification,Row,Col,Alert,message,Image } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import http from 'axios'
import OSS from 'ali-oss'
import { ExclamationCircleOutlined } from '@ant-design/icons';
import UploadPicture from './index'
import {replacePicture} from 'api/index'
import { connect } from 'react-redux'
const { confirm } = Modal; 
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

class App extends React.Component {
  state = {
    previewVisible: false,
    previewImage: '',
    previewTitle: '',
    checkVisible:false,
    id:'',
    pictureType:'',
    fileList: this.props.value?this.props.value.map(i=>{
      return {url:i.pictureUrl||i.url,status:'done',pictureType:i.pictureType,id:i.id}
    }):[],
    disabled:this.props.disabled,
    picRealistic:''
  };

  setPhoto = (value) => {
    this.setState({
      picRealistic:value
    })
  }

  componentWillReceiveProps(nextProps){
    // if(this.props.disabled===nextProps.disabled&&JSON.stringify(nextProps.value)===JSON.stringify(this.props.value)) return
    // let self = this;
    // self.setState({
    //   disabled:nextProps.disabled
    // })
    // const data = nextProps.value?nextProps.value.map(i=>{
    //   return {url:i.pictureUrl||i.url,status:'done'}
    // }):[]
    // self.setState({ fileList:data});
  }

  handleCancel = () => this.setState({ previewVisible: false,checkVisible:false });

  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    });
  };

  handleChange = ({ fileList }) => {
    this.setState({ fileList:fileList.filter(i=>i.status==='done') },()=>{
      this.props.setPhoto(this.state.fileList)
    });
  };

  handleMove = (file) =>{
    if(this.state.disabled) return false

    if(!this.props.userBtnRole.includes('WORD_RELACE')) return true

     this.setState({
      previewImage:file.url||file.pictureUrl,
      pictureType:file.pictureType,
      id:file.id
     })

     if( window.location.href.indexOf('/word/wordInfo')===-1){
       return true
     }
   
       
      const _this = this

      confirm({
        title: '请选择删除或者替换该图片',
        icon: <ExclamationCircleOutlined />,
        content: '二选一',
        okText:"替换",
        cancelText:'删除',
        onOk() {
          _this.setState({
            checkVisible:true
          })
        },
        onCancel() {
          _this.setState({
              fileList:[..._this.state.fileList].filter(i=>i.url!==file.url)
            },()=>{
              _this.props.setPhoto(_this.state.fileList)
            })
        },
      });
    
    return new Promise((resolve, reject) => {
      resolve(false)
    });
  }
  
  handleOkFn = async() => {
    const _this = this
    if(!this.state.picRealistic) {
      message.error('请上传替换的图片');
      return
    }
     try{
      await replacePicture({
        id: this.state.id,
        pictureType: this.state.pictureType,
        pictureUrl: this.state.picRealistic,
        pictureUrlOld: this.state.previewImage,
        flowWordId: window.location.href.slice(window.location.href.indexOf('id=')+3)
      })
      message.success('替换成功');
      _this.setState({
        checkVisible:false,
        previewImage:'',
        pictureType:'',
        picRealistic:''
      })
      this.props.updateInfo()
     } catch(err){
      message.error('替换失败，请重试');
     }
  }

  customRequest = (file) => {
    var suffix = file.file.name.substr(file.file.name.indexOf('.')) // 获取文件后缀名
    var filename = new Date().getTime() + suffix // 为文件命名


    const token =  window.location.href.indexOf('/prd') === -1 ?localStorage.getItem('token-llx-test'):localStorage.getItem('token-llx')


    http({
      method: 'post',
      url:  window.location.href.indexOf('/prd')===-1?'http://139.224.81.105:19999/qia-cloud-filesystem/OSS/companies/getStsToken':'http://139.224.81.105:9999/qia-cloud-filesystem/OSS/companies/getStsToken',
      headers: { 'Authorization': 'Bearer ' + token}
    }).then(res => {
      const fileData = res
      var bucket = 'middle-file'
      var region = 'oss-cn-shanghai'
      var type = ''
      const client = new OSS({
        region,
        accessKeyId: fileData.accessKeyId,
        accessKeySecret: fileData.accessKeySecret,
        stsToken: fileData.stsToken,
        bucket
      })
      type = 'image'
      client.multipartUpload(type + '/' + filename, file.file).then((result) => {
        var url = result.res.requestUrls[0]
        var length = url.lastIndexOf('?')
        var getUrl = length > 0 ? url.substr(0, length) : url // 文件最终路径

        this.setState({
          fileList:[...this.state.fileList,{url:getUrl,status: 'done'}].filter(i=>i.status==='done')
        },()=>{
          this.props.setPhoto(this.state.fileList)
        })
        


      }).catch(function(err) {
        notification.error({
          description:'上传失败',
          duration:1
        })
      })
  }).catch(err=>{
    notification.error({
      description:'上传失败',
      duration:1
    })
  })
}

  render() {
    const { previewVisible, previewImage, fileList, previewTitle ,disabled ,checkVisible} = this.state;
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>点击上传</div>
      </div>
    );
    return (
      <>
        <Upload
          action="#"
          accept="image/*"
          multiple
          listType="picture-card"
          fileList={fileList}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
          onRemove={this.handleMove}
          customRequest={this.customRequest}
        >
          {fileList.length >= 20 || disabled ? null : uploadButton}
        </Upload>
        
        <Modal
          visible={previewVisible}
          title={previewTitle}
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>

        <Modal
          width={500}
          visible={checkVisible}
          title={'替换图片'}
          onOk={this.handleOkFn}
          onCancel={this.handleCancel}
        >
           <Alert className="edit-alert" message='请上传替换成为的图片，此操作不可撤' type="success" />
          <Row>
            <Col span={4}></Col>
            <Col span={11}>
            <Image
             width={100}
             height={100}
             src={this.state.previewImage}
           />
             </Col>
            <Col span={4}>
              <UploadPicture pictureList={this.state.picRealistic}  setPhoto={(value)=>this.setPhoto(value)}></UploadPicture>
            </Col>
            <Col span={4}></Col>
          </Row>
        </Modal>
      </>
    );
  }
}

export default connect(state=>{
  return {
    userBtnRole:state.userBtnRole
  }
})(App);